package com.jiemengshi.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.jiemengshi.server.model.Attachment;
import com.jiemengshi.server.qiniu.PutPolicy;
import com.jiemengshi.server.qiniu.QiniuCallbackObj;
import com.jiemengshi.server.service.AdminUserService;
import com.jiemengshi.server.service.QiniuService;
import com.jiemengshi.server.util.ApiJson;
import com.jiemengshi.server.util.ApiResult;
import com.jiemengshi.server.util.ErrorCodeMsg;
import com.jiemengshi.server.util.PrjException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by MingQi on 2017/10/28.
 */
@Controller
@RequestMapping(value = {"/attachment"}, produces = {"application/json;charset=UTF-8"})
public class QiniuController {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${api_domain_attachment}")
    private String apiDomainAttachment;
    
    @Value("${qiniu_image_access_domain}")
    private String qiniuImageAccessDomain;

    @Value("${qiniu_voice_access_domain}")
    private String qiniuVoiceAccessDomain;
    
    @Value("${qiniu_image_bucket_name}")
    private String imageBucketName;

    @Value("${qiniu_voice_bucket_name}")
    private String voiceBucketName;
    
    @Value("${qiniu_ak}")
    private String accessKey;

    @Value("${qiniu_sk}")
    private String secretKey;

    @Autowired
    private QiniuService qiniuService;

    @ResponseBody
    @RequestMapping("/qiniu/image/callback")
    public String qiniuCallbackImage(HttpServletRequest request, QiniuCallbackObj callbackObj) {
        try {
            Attachment attachment = qiniuService.saveQiniuAttachment(callbackObj);
            if(attachment != null){
                JSONObject ret = new JSONObject();
                ret.put("attachmentId", attachment.getId());
                ret.put("url", qiniuImageAccessDomain+"/"+callbackObj.getKey());

                return ApiResult.writeData(ret);
            } else
                throw new PrjException(ErrorCodeMsg.ATTACHMENT_SAVE_ERROR);
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/qiniu/voice/callback")
    public String qiniuCallbackVoice(HttpServletRequest request, QiniuCallbackObj callbackObj) {
        try {
            Attachment attachment = qiniuService.saveQiniuAttachment(callbackObj);
            if(attachment != null){
                JSONObject ret = new JSONObject();
                ret.put("attachmentId", attachment.getId());
                ret.put("url", qiniuVoiceAccessDomain+"/"+callbackObj.getKey());

                return ApiResult.writeData(ret);
            } else
                throw new PrjException(ErrorCodeMsg.ATTACHMENT_SAVE_ERROR);
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/qiniu/image/uptoken")
    public String getQiniuImageUptoken(HttpServletRequest request){
        try {
            int userAdminId = 0, userId = 0;

            Object sAdminInfo = request.getSession().getAttribute("adminInfo");
            if (sAdminInfo != null) {
                userAdminId = Integer.parseInt(((String) sAdminInfo).split("_")[0]);
            } else {
                Object sUserInfo = request.getSession().getAttribute("userInfo");

                if(sUserInfo != null)
                    userId = Integer.parseInt(((String) sUserInfo).split("_")[0]);
            }
            if(userAdminId == 0 && userId == 0)
                throw new PrjException(ErrorCodeMsg.USER_NOT_LOGIN);
            
            PutPolicy policy = new PutPolicy(imageBucketName, accessKey, secretKey);

            String callbackUrl = apiDomainAttachment + "/qiniu/image/callback";
            String callbackBody = "key=$(key)&hash=$(etag)&fsize=$(fsize)&fname=${fname}&name=$(x:fileName)&mimeType=$(mimeType)&userAdminId=" + userAdminId + "&userId=" + userId;

            policy.setCallbackUrl(callbackUrl);
            policy.setCallbackBody(callbackBody);
            policy.setSaveKey("$(etag)" + "/$(x:fileName)");
            policy.setMimeLimit("image/*");
            
            return ApiResult.writeData(policy.getToken());
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }
    
    @ResponseBody
    @RequestMapping("/qiniu/voice/uptoken")
    public String getQiniuVoiceUptoken(HttpServletRequest request){
        try {
            int userAdminId = 0, userId = 0;

            Object sAdminInfo = request.getSession().getAttribute("adminInfo");
            if (sAdminInfo != null) {
                userAdminId = Integer.parseInt(((String) sAdminInfo).split("_")[0]);
            } else {
                Object sUserInfo = request.getSession().getAttribute("userInfo");

                if(sUserInfo != null)
                    userId = Integer.parseInt(((String) sUserInfo).split("_")[0]);
            }
            if(userAdminId == 0 && userId == 0)
                throw new PrjException(ErrorCodeMsg.USER_NOT_LOGIN);
            
            PutPolicy policy = new PutPolicy(voiceBucketName, accessKey, secretKey);

            String callbackUrl = apiDomainAttachment + "/qiniu/voice/callback";
            String callbackBody = "key=$(key)&hash=$(etag)&fsize=$(fsize)&fname=${fname}&name=$(x:fileName)&mimeType=$(mimeType)&userAdminId=" + userAdminId + "&userId=" + userId;

            policy.setCallbackUrl(callbackUrl);
            policy.setCallbackBody(callbackBody);
            policy.setSaveKey("$(etag)" + "/$(x:fileName)");

            return ApiResult.writeData(policy.getToken());
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/announcement/image/get")
    public String getAnnouncementImage(){
        try {
            Attachment image = qiniuService.getAnnouncementImage();

            return ApiResult.writeData(qiniuImageAccessDomain + "/" + image.getQiniuKey());
        } catch (Exception e) {
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/voice/url")
    public String getVoiceUrl(int voiceRecordId){
        try {
            Attachment voice = qiniuService.getAttachmentById(voiceRecordId);

            return ApiResult.writeData(qiniuVoiceAccessDomain + "/" + voice.getQiniuKey());
        } catch (Exception e) {
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }
}
